package com.hp.team.bookstore.dbutil.init;

import java.util.Calendar;

import com.hp.team.bookstore.dbutil.Utils;
import com.hp.team.bookstore.dbutil.dao.DAOFactory;
import com.hp.team.bookstore.dbutil.dao.HibernateUtil;
import com.hp.team.bookstore.dbutil.dao.order.SalesOrderHibernateDAO;
import com.hp.team.bookstore.dbutil.dao.profile.UserHibernateDAO;
import com.hp.team.bookstore.model.order.SOStatus;
import com.hp.team.bookstore.model.order.SalesOrder;
import com.hp.team.bookstore.model.profile.User;

public class SalesOrderInitializer {

	private static UserHibernateDAO userDAO;

	private static SalesOrderHibernateDAO orderDAO;

	private static Calendar baseDate;

	static {
		DAOFactory daoFactory = new DAOFactory();
		userDAO = daoFactory.getUserDAO();
		orderDAO = daoFactory.getSalesOrderDAO();

	}

	public static void init() {

		orderDAO.setSession(HibernateUtil.getSessionFactory().getCurrentSession());
		HibernateUtil.beginWriteTransaction();

		for (int i = 0; i < 30; i++) {
			SalesOrder order = createSalesOrder(i);
			orderDAO.makePersistent(order);
		}

		HibernateUtil.commitTransaction();
	}

	public static SalesOrder createSalesOrder(long id) {

		SalesOrder order = new SalesOrder();

		if (id % 5 == 0) {
			order.setStatus(SOStatus.NEW);
		} else if (id % 2 == 0) {
			order.setStatus(SOStatus.READY_TO_PICK);
		} else if (id % 3 == 0) {
			order.setStatus(SOStatus.PICKED);
		} else {
			order.setStatus(SOStatus.SHIPPED);
		}

		baseDate = Calendar.getInstance();
		baseDate.add(Calendar.MONTH, -6);
		baseDate.add(Calendar.DAY_OF_MONTH, 10 * ((int) id + 1));
		order.setDate(baseDate);

		User user = userDAO.findById(id % 2 == 0 ? 9L : 10L, true);
		order.setCreator(user);

		double subTotal = Utils.generateRandomNumber(10, 100);
		double shippingFees = 0.05 * subTotal;
		double taxes = 0.03 * subTotal;

		order.setShippingFees(taxes);
		order.setShippingFees(shippingFees);
		order.setSubTotalPrice(subTotal);
		order.setGrandTotalPrice(subTotal + shippingFees + taxes);

		return order;
	}

}
